package net.manelizzard.equipmentexplorer.activity;

import java.util.List;

import net.manelizzard.equipmentexplorer.R;
import net.manelizzard.equipmentexplorer.util.Constants;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class ActivityMain extends Activity {
	private final String TAG = "Activity Main";
	
	// UX Object references
	private EditText mEditTextSerialNumber;
	private ProgressDialog mProgressDialog;
	
	// SharedPreferences
	private SharedPreferences mSharedPreferences;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		
		init();
		getViews();
	}
	
    /**
     * Initializes the Activity elements
     */
	private void init() {
		mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		/** Parse initialization **/
		Parse.initialize(this, Constants.PARSE.APP_ID, Constants.PARSE.CLIENT_KEY);
	}
	
    /**
     * Obtain UX object references
     */
	private void getViews() {
		mEditTextSerialNumber = (EditText) findViewById(R.id.editTextSerialNumber);
		mProgressDialog = new ProgressDialog(this);
	}
	
    /**
     * Handles the click event in the screen buttons
     * 
     * @param v The {@link View} firing the event
     */
	public void onBtnClick(View v) {
		switch(v.getId()) {
		case R.id.btnLogout:
			
			// Changes persistant logged status
			if(mSharedPreferences != null) {
				mSharedPreferences.edit().remove(Constants.PREFERENCES.LOGGED).commit();
			}
			
			// ActivityLogin Intent
			Intent loginIntent = new Intent(this, ActivityLogin.class);
			startActivity(loginIntent);
			
			// Closes the current Activity
			finish();
			break;
		case R.id.btnScanQr:
			
			IntentIntegrator integrator = new IntentIntegrator(this);
			integrator.initiateScan();
			
			break;
		case R.id.btnSerialNumber:
			
			if(mEditTextSerialNumber.getText().toString().equalsIgnoreCase(Constants.VALIDATION.EMPTY_FIELD))
				Toast.makeText(this, getString(R.string.toast_err_enter_serial), Toast.LENGTH_LONG).show();
			else
				doSerialNumberSearch(mEditTextSerialNumber.getText().toString());
			
			break;
		}
	}
	
	/**
	 * Method called after scanning QR
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		  IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
		  
		  if (scanResult != null && scanResult.getContents() != null) {
			  Log.i(TAG, "Scan result: " + scanResult.getContents());
			  
			  // Detect APP LOGIC TOKEN
			  if(scanResult.getContents().startsWith(Constants.VALIDATION.QR_VALIDATION_TOKEN)) {
				  // The QR was generated for the app
				  // Obtain the serialNumber
				  String serialNumber = scanResult.getContents().substring(Constants.VALIDATION.QR_VALIDATION_TOKEN.length(), scanResult.getContents().length());
				  Log.i(TAG, "Serial number: " + serialNumber);
				  doSerialNumberSearch(serialNumber);
			  } else {
				  // QR is not valid, so inform the user
				  Toast.makeText(this, getString(R.string.toast_err_qr_not_valid), Toast.LENGTH_LONG).show();
			  }
		  }
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		// Dismisses dialog if activity is no longer visible
		if(mProgressDialog != null && mProgressDialog.isShowing())
			mProgressDialog.dismiss();
	}
	
	/**
	 * Connects with Parse services and retrieves the object desired
	 * 
	 * @param serialNumber The serial number of the equipment to be retrieved
	 */
	private void doSerialNumberSearch(String serialNumber) {
		if(mProgressDialog != null) {
			mProgressDialog.setMessage(getString(R.string.pd_retrieving));
			mProgressDialog.show();
		}
		
		ParseQuery query = new ParseQuery("ModelEquipment");
		query.whereContains(Constants.EQUIPMENT.SERIAL_NUMBER, serialNumber);
		
		query.findInBackground(new FindCallback() {

			@Override
			public void done(List<ParseObject> objects, ParseException parseException) {
				// Dismisses progress dialog
				if(mProgressDialog != null && mProgressDialog.isShowing())
					mProgressDialog.dismiss();
				
				if (parseException == null) { 
					// Everything was OK
					
					if(objects == null || objects.isEmpty()) {
						objectRetrievalFailed(ParseException.OBJECT_NOT_FOUND);	
					} else {
						// Object found	
					}
				} else {
					Log.e(TAG, "Parse Exception: " + parseException.getCode());
					objectRetrievalFailed(parseException.getCode());
				}
			}
		 });
	}
	
	/**
	 * Shows error message to user
	 * 
	 * @param parseExceptionCode The code of the ParseException
	 */
	private void objectRetrievalFailed(int parseExceptionCode) {
		switch(parseExceptionCode) {

			/** Equipment not found **/
			case ParseException.OBJECT_NOT_FOUND:
				Toast.makeText(this, getString(R.string.toast_err_no_equipment_found), Toast.LENGTH_LONG).show();
				break;
		
			/** Generic Parse error **/
			case ParseException.INTERNAL_SERVER_ERROR:
				Toast.makeText(this, getString(R.string.toast_err_server_generic), Toast.LENGTH_LONG).show();
				break;
		
			/** Timeout error **/
			case ParseException.TIMEOUT:
				Toast.makeText(this, getString(R.string.toast_err_server_timeout), Toast.LENGTH_LONG).show();
				break;
			}
	}
}
